package wang.hu.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import wang.hu.bos.utils.MailUtils;
import wang.hu.crm.domain.Customer;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmsQueueTemplate;

	@Action(value = "customer_sendMsg")
	public String sendMsg() {
		String checkCode = RandomStringUtils.randomNumeric(6);
		ServletActionContext.getRequest().getSession()
				.setAttribute("checkCode", checkCode);
		System.out.println("生成的手机验证码为:" + checkCode);
		final String content = "尊敬的用户您好,本次验证码为:" + checkCode
				+ ",服务电话:400-8008888";

		jmsQueueTemplate.send("bos_msg", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("content", content);
				return mapMessage;
			}
		});
		return NONE;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "./signup-success.html"),
			@Result(name = "input", type = "redirect", location = "./signup.html") })
	public String regist() {
		String code1 = (String) ServletActionContext.getRequest().getSession()
				.getAttribute("checkCode");
		String code2 = ServletActionContext.getRequest().getParameter(
				"checkCode");
		if (code1 == null || !code1.equals(code2)) {

			return INPUT;
		} else {
			WebClient
					.create("http://localhost:9111/crm_management/services/customerService/savecustomer")
					.type(MediaType.APPLICATION_JSON).post(model);
			String code = RandomStringUtils.randomNumeric(20);
			redisTemplate.opsForValue().set(model.getTelephone(), code, 24,
					TimeUnit.HOURS);
			MailUtils.sendMail("<h1>激活邮件</h1>",
					"<h3>尊敬的用户您好,请点击一下链接:<a href='" + MailUtils.activeUrl
							+ "?telephone=" + model.getTelephone() + "&code="
							+ code + "'>点击激活</a></h3>", model.getEmail());
			return SUCCESS;
		}
	}

	// 绑定激活邮箱执行方法

	@Action(value = "customer_activeMail", results = { @Result(name = "success", location = "./login.html") })
	public String activeMail() {
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=UTF-8");
		String code = ServletActionContext.getRequest().getParameter("code");
		String activeCode = redisTemplate.opsForValue().get(
				model.getTelephone());
		if (activeCode == null || !code.equals(activeCode)) {
			// 激活失败
			try {
				ServletActionContext.getResponse().getWriter()
						.println("激活码验证失败!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			Customer customer = WebClient
					.create("http://localhost:9111/crm_management/services/customerService/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() == null || customer.getType() != 1) {
				WebClient.create(
						"http://localhost:9111/crm_management/services/customerService/changetype/"
								+ model.getTelephone()).get();
			} else {
				try {
					ServletActionContext.getResponse().getWriter()
							.println("你已经激活过了!");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			redisTemplate.delete(model.getTelephone());
		}

		return SUCCESS;
	}

	@Action(value = "customer_login", results = {
			@Result(name = "success", location = "index.html#/myhome.html", type = "redirect"),
			@Result(name = "login", location = "./login.html", type = "redirect") })
	public String login() {
		String code1 = ServletActionContext.getRequest().getParameter(
				"checkcode");
		String code2 = (String) ServletActionContext.getRequest().getSession()
				.getAttribute("code");
		if (!code1.equalsIgnoreCase(code2)) {
			return LOGIN;
		}
		Customer customer = WebClient
				.create("http://localhost:9111/crm_management/services/customerService/login?telephone="
						+ model.getTelephone()
						+ "&password="
						+ model.getPassword())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer == null) {
			// 登录失败
			return LOGIN;

		} else {
			// 登录成功
			ServletActionContext.getRequest().getSession()
					.setAttribute("customer", customer);
			return SUCCESS;
		}
	}
}
